from fastapi import APIRouter, UploadFile, File, HTTPException
from fastapi.responses import JSONResponse
import os
import uuid
from datetime import datetime

router = APIRouter()

# 上传文件存储目录
UPLOAD_DIR = "uploads/avatars"
if not os.path.exists(UPLOAD_DIR):
    os.makedirs(UPLOAD_DIR, exist_ok=True)

@router.post("/upload")
async def upload_avatar(file: UploadFile = File(...)):
    """头像上传接口 - 上传并返回可访问URL"""
    
    # 验证文件类型
    allowed_extensions = {'.jpg', '.jpeg', '.png', '.gif', '.bmp'}
    file_ext = os.path.splitext(file.filename)[1].lower()
    
    if file_ext not in allowed_extensions:
        return JSONResponse(
            content={
                "error": "不支持的文件类型，请上传图片文件",
                "url": ""
            }
        )
    
    # 生成唯一文件名
    unique_filename = f"{uuid.uuid4().hex}{file_ext}"
    file_path = os.path.join(UPLOAD_DIR, unique_filename)
    
    try:
        # 保存文件
        contents = await file.read()
        if len(contents) > 5 * 1024 * 1024:  # 5MB限制
            return JSONResponse(
                content={
                    "error": "文件大小超过5MB限制",
                    "url": ""
                }
            )
            
        with open(file_path, "wb") as f:
            f.write(contents)
        
        # 生成可访问的URL
        file_url = f"http://192.168.3.191:8000/uploads/avatars/{unique_filename}"
        
        return JSONResponse(
            content={
                "error": "",
                "url": file_url
            }
        )
        
    except Exception as e:
        return JSONResponse(
            content={
                "error": f"上传失败: {str(e)}",
                "url": ""
            }
        )